import { ref, toRefs, unref } from "vue";
import useDictStore from "@/store/modules/dict";
import { getDicts, initDict as initDictApi } from "@/api/system/dict/data";
import XEUtils from "xe-utils";
/**
 * 获取字典数据
 */
export function useDict(...args: any[]) {
    const res = ref<any>({});
    return (() => {
        args.forEach((dictType: any) => {
            res.value[dictType] = [];
            const dicts = useDictStore().getDict(dictType);
            if (dicts) {
                res.value[dictType] = dicts;
            } else {
                getDicts(dictType).then((resp) => {
                    res.value[dictType] = resp.data.map((p: any) => ({
                        label: p.dictLabel,
                        value: p.dictValue,
                        elTagType: p.listClass,
                        elTagClass: p.cssClass,
                        ...p,
                    }));
                    useDictStore().setDict(dictType, res.value[dictType]);
                });
            }
        });
        return unref(res.value);
    })();
}
/**
 * 判断字典是否被缓存了
 * @param args
 * @returns 没有被缓存的字典key
 */
export function useHasDict(...args: any[]) {
    const res = new Set();
    return (() => {
        args.forEach((dictType: String) => {
            if (!useDictStore().dictKey.has(dictType)) {
                res.add(dictType);
            }
        });
        return res;
    })();
}
/**
 * 初始化所有字典
 */
export function initSysDict() {
    initDictApi().then((res) => {
        const dictKeys = <Array<any>>[];
        const dicts = <Array<any>>[];
        XEUtils.arrayEach(res.data, (item: any) => {
            for (const key in item) {
                const dictItems = <Array<any>>[];
                dictKeys.push(key);
                XEUtils.arrayEach(item[key], (itemDict: any) => {
                    dictItems.push({ label: itemDict.dictLabel, value: itemDict.dictValue, elTagType: itemDict.listClass, elTagClass: itemDict.cssClass, ...itemDict });
                });
                dicts.push({ key: key, value: dictItems });
            }
        });
        useDictStore().initDict(dicts, dictKeys);
    });
}
